// 销售漏斗功能实现

// 使用全局函数，不再使用ES模块导入

// 漏斗数据状态
const salesFunnelState = {
    // 销售阶段数据
    stages: [
        { id: 'lead', name: '线索', value: 500, conversionRate: 100 },
        { id: 'contact', name: '初次接触', value: 350, conversionRate: 70 },
        { id: 'qualified', name: '资格确认', value: 220, conversionRate: 44 },
        { id: 'proposal', name: '方案提案', value: 135, conversionRate: 27 },
        { id: 'negotiation', name: '商务谈判', value: 80, conversionRate: 16 },
        { id: 'closed', name: '成交', value: 45, conversionRate: 9 }
    ],
    // 时间周期
    currentPeriod: 'quarter', // quarter, month, year
    // 比较周期
    showComparison: false,
    comparisonPeriod: 'previous',
    // 对比数据
    comparisonStages: [],
    // 图表引用
    funnelChart: null,
    trendChart: null
};

// 初始化销售漏斗
function initSalesFunnel() {
    // 监听路由变更事件
    window.addEventListener('routeChanged', (e) => {
        if (e.detail.route === 'sales') {
            // 延迟一点时间初始化图表，确保DOM已经渲染
            setTimeout(() => {
                initFunnelCharts();
                initPeriodToggle();
                initComparisonToggle();
            }, 100);
        }
    });
    
    // 初始加载时，如果当前是销售漏斗页面，则初始化
    if (document.getElementById('sales').classList.contains('active')) {
        setTimeout(() => {
            initFunnelCharts();
            initPeriodToggle();
            initComparisonToggle();
        }, 100);
    }
}

// 初始化漏斗图表
function initFunnelCharts() {
    // 初始化主要漏斗图
    initMainFunnelChart();
    
    // 初始化趋势图表
    initTrendChart();
    
    // 更新阶段统计数据
    updateStageStatistics();
}

// 初始化主要漏斗图
function initMainFunnelChart() {
    const ctx = document.getElementById('funnelChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (salesFunnelState.funnelChart) {
        salesFunnelState.funnelChart.destroy();
    }
    
    // 准备数据
    const labels = salesFunnelState.stages.map(stage => stage.name);
    const values = salesFunnelState.stages.map(stage => stage.value);
    
    // 创建渐变色
    const gradientColors = [
        'rgba(52, 152, 219, 0.8)',
        'rgba(155, 89, 182, 0.8)',
        'rgba(46, 204, 113, 0.8)',
        'rgba(243, 156, 18, 0.8)',
        'rgba(231, 76, 60, 0.8)',
        'rgba(26, 188, 156, 0.8)'
    ];
    
    // 准备漏斗图数据
    const data = {
        labels: labels,
        datasets: [
            {
                data: values,
                backgroundColor: gradientColors,
                borderColor: '#fff',
                borderWidth: 2,
                hoverBackgroundColor: gradientColors.map(color => color.replace('0.8', '1')),
                hoverBorderWidth: 3
            }
        ]
    };
    
    // 配置漏斗图选项
    const options = {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            },
            tooltip: {
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                titleColor: '#fff',
                bodyColor: '#fff',
                callbacks: {
                    label: function(context) {
                        const value = context.parsed.x;
                        const stage = salesFunnelState.stages[context.dataIndex];
                        const firstStageValue = salesFunnelState.stages[0].value;
                        const prevValue = context.dataIndex > 0 ? salesFunnelState.stages[context.dataIndex - 1].value : firstStageValue;
                        
                        const fromFirstStageRate = ((value / firstStageValue) * 100).toFixed(1);
                        const fromPrevStageRate = context.dataIndex > 0 ? ((value / prevValue) * 100).toFixed(1) : '100.0';
                        
                        return [
                            `数量: ${value.toLocaleString()}`,
                            `占比(从头): ${fromFirstStageRate}%`,
                            `转化率(从上): ${fromPrevStageRate}%`
                        ];
                    }
                }
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                grid: {
                    display: false
                }
            },
            y: {
                grid: {
                    display: false
                }
            }
        },
        animation: {
            duration: 1000,
            easing: 'easeOutQuart'
        }
    };
    
    // 创建水平条形图作为漏斗图
    salesFunnelState.funnelChart = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: options
    });
}

// 初始化趋势图表
function initTrendChart() {
    const ctx = document.getElementById('trendChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (salesFunnelState.trendChart) {
        salesFunnelState.trendChart.destroy();
    }
    
    // 准备数据
    let labels, currentData, comparisonData = [];
    
    switch (salesFunnelState.currentPeriod) {
        case 'month':
            labels = ['第1周', '第2周', '第3周', '第4周'];
            currentData = [45, 52, 58, 45]; // 成交数量
            comparisonData = [38, 42, 50, 36]; // 对比周期成交数量
            break;
        case 'quarter':
            labels = ['1月', '2月', '3月'];
            currentData = [138, 145, 167];
            comparisonData = [120, 132, 145];
            break;
        case 'year':
            labels = ['Q1', 'Q2', 'Q3', 'Q4'];
            currentData = [450, 480, 520, 560];
            comparisonData = [410, 440, 475, 500];
            break;
        default:
            labels = ['1月', '2月', '3月'];
            currentData = [138, 145, 167];
            comparisonData = [120, 132, 145];
    }
    
    // 准备图表数据
    const datasets = [
        {
            label: getCurrentPeriodLabel(),
            data: currentData,
            borderColor: '#3498db',
            backgroundColor: 'rgba(52, 152, 219, 0.1)',
            borderWidth: 2,
            tension: 0.4,
            fill: true
        }
    ];
    
    // 如果显示对比数据，则添加第二个数据集
    if (salesFunnelState.showComparison) {
        datasets.push({
            label: getComparisonPeriodLabel(),
            data: comparisonData,
            borderColor: '#e74c3c',
            backgroundColor: 'rgba(231, 76, 60, 0.1)',
            borderWidth: 2,
            tension: 0.4,
            fill: true,
            borderDash: [5, 5]
        });
    }
    
    // 创建趋势图
    salesFunnelState.trendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: datasets
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff'
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 更新阶段统计数据
function updateStageStatistics() {
    const stagesContainer = document.getElementById('stageStatistics');
    if (!stagesContainer) return;
    
    // 清空容器
    stagesContainer.innerHTML = '';
    
    // 渲染每个阶段的统计卡片
    salesFunnelState.stages.forEach((stage, index) => {
        const card = document.createElement('div');
        card.className = 'stage-card';
        
        // 计算转化率
        const prevStageValue = index > 0 ? salesFunnelState.stages[index - 1].value : stage.value;
        const conversionFromPrev = index > 0 ? ((stage.value / prevStageValue) * 100).toFixed(1) : '100.0';
        
        // 为不同阶段设置不同的颜色
        const stageColors = [
            'primary', 'secondary', 'success', 'warning', 'danger', 'info'
        ];
        const stageColor = stageColors[index % stageColors.length];
        
        card.innerHTML = `
            <div class="stage-header">
                <h4 class="stage-name">${stage.name}</h4>
                <span class="stage-number">${index + 1}</span>
            </div>
            <div class="stage-body">
                <div class="stage-metrics">
                    <div class="stage-metric">
                        <span class="metric-label">客户数量</span>
                        <span class="metric-value">${stage.value.toLocaleString()}</span>
                    </div>
                    <div class="stage-metric">
                        <span class="metric-label">总体转化率</span>
                        <span class="metric-value">${stage.conversionRate}%</span>
                    </div>
                    <div class="stage-metric">
                        <span class="metric-label">阶段转化率</span>
                        <span class="metric-value ${parseFloat(conversionFromPrev) > 70 ? 'positive' : 'negative'}">${conversionFromPrev}%</span>
                    </div>
                </div>
                <div class="stage-progress-container">
                    <div class="stage-progress-bar">
                        <div class="stage-progress ${stageColor}" style="width: ${stage.conversionRate}%"></div>
                    </div>
                    <div class="stage-progress-text">${stage.conversionRate}% of total</div>
                </div>
            </div>
        `;
        
        stagesContainer.appendChild(card);
    });
    
    // 更新总体统计
    updateOverallStatistics();
}

// 更新总体统计
function updateOverallStatistics() {
    const totalLeadsElem = document.getElementById('totalLeads');
    const totalClosedElem = document.getElementById('totalClosed');
    const overallConversionElem = document.getElementById('overallConversion');
    const avgDealSizeElem = document.getElementById('avgDealSize');
    
    if (!totalLeadsElem || !totalClosedElem || !overallConversionElem || !avgDealSizeElem) return;
    
    const totalLeads = salesFunnelState.stages[0].value;
    const totalClosed = salesFunnelState.stages[salesFunnelState.stages.length - 1].value;
    const overallConversion = ((totalClosed / totalLeads) * 100).toFixed(1);
    
    // 模拟平均成交金额 (根据不同周期调整)
    let avgDealSize;
    switch (salesFunnelState.currentPeriod) {
        case 'month':
            avgDealSize = 125000;
            break;
        case 'quarter':
            avgDealSize = 135000;
            break;
        case 'year':
            avgDealSize = 150000;
            break;
        default:
            avgDealSize = 135000;
    }
    
    totalLeadsElem.textContent = totalLeads.toLocaleString();
    totalClosedElem.textContent = totalClosed.toLocaleString();
    overallConversionElem.textContent = overallConversion + '%';
    avgDealSizeElem.textContent = formatCurrency(avgDealSize);
}

// 初始化周期切换
function initPeriodToggle() {
    const periodBtns = document.querySelectorAll('.period-toggle-btn');
    
    periodBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有按钮的活动状态
            document.querySelectorAll('.period-toggle-btn').forEach(b => {
                b.classList.remove('active');
            });
            
            // 添加当前按钮的活动状态
            btn.classList.add('active');
            
            // 更新当前周期
            const period = btn.dataset.period;
            salesFunnelState.currentPeriod = period;
            
            // 更新数据和图表
            updateFunnelData();
            initFunnelCharts();
        });
    });
}

// 初始化对比切换
function initComparisonToggle() {
    const comparisonToggle = document.getElementById('comparisonToggle');
    if (!comparisonToggle) return;
    
    comparisonToggle.addEventListener('change', function() {
        salesFunnelState.showComparison = this.checked;
        
        // 更新趋势图
        initTrendChart();
        
        // 更新对比周期选择器显示
        const comparisonPeriodContainer = document.getElementById('comparisonPeriodContainer');
        if (comparisonPeriodContainer) {
            comparisonPeriodContainer.style.display = this.checked ? 'block' : 'none';
        }
    });
    
    // 初始化对比周期选择
    const comparisonPeriodSelect = document.getElementById('comparisonPeriodSelect');
    if (comparisonPeriodSelect) {
        comparisonPeriodSelect.addEventListener('change', function() {
            salesFunnelState.comparisonPeriod = this.value;
            initTrendChart();
        });
    }
}

// 更新漏斗数据
function updateFunnelData() {
    // 根据不同周期生成不同的随机数据（模拟真实场景）
    const baseValue = salesFunnelState.currentPeriod === 'year' ? 2000 : 
                     salesFunnelState.currentPeriod === 'quarter' ? 500 : 200;
    
    // 生成新的随机数据，但保持漏斗形状
    let prevValue = baseValue;
    salesFunnelState.stages = [
        { id: 'lead', name: '线索', value: prevValue, conversionRate: 100 }
    ];
    
    // 各阶段转换比例（随机但有一定范围）
    const conversionRatios = [
        Math.random() * 0.1 + 0.65, // 65%-75% 线索到初次接触
        Math.random() * 0.1 + 0.55, // 55%-65% 初次接触到资格确认
        Math.random() * 0.1 + 0.55, // 55%-65% 资格确认到方案提案
        Math.random() * 0.1 + 0.50, // 50%-60% 方案提案到商务谈判
        Math.random() * 0.1 + 0.50  // 50%-60% 商务谈判到成交
    ];
    
    // 生成后续阶段数据
    const stageNames = ['初次接触', '资格确认', '方案提案', '商务谈判', '成交'];
    const stageIds = ['contact', 'qualified', 'proposal', 'negotiation', 'closed'];
    
    for (let i = 0; i < stageNames.length; i++) {
        prevValue = Math.round(prevValue * conversionRatios[i]);
        const conversionRate = Math.round((prevValue / baseValue) * 100);
        
        salesFunnelState.stages.push({
            id: stageIds[i],
            name: stageNames[i],
            value: prevValue,
            conversionRate: conversionRate
        });
    }
}

// 获取当前周期标签
function getCurrentPeriodLabel() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const quarter = Math.floor((month - 1) / 3) + 1;
    
    switch (salesFunnelState.currentPeriod) {
        case 'month':
            return `${year}年${month}月`;
        case 'quarter':
            return `${year}年Q${quarter}`;
        case 'year':
            return `${year}年`;
        default:
            return `${year}年Q${quarter}`;
    }
}

// 获取对比周期标签
function getComparisonPeriodLabel() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const quarter = Math.floor((month - 1) / 3) + 1;
    
    if (salesFunnelState.comparisonPeriod === 'previous') {
        switch (salesFunnelState.currentPeriod) {
            case 'month':
                const prevMonth = month === 1 ? 12 : month - 1;
                const prevMonthYear = month === 1 ? year - 1 : year;
                return `${prevMonthYear}年${prevMonth}月`;
            case 'quarter':
                const prevQuarter = quarter === 1 ? 4 : quarter - 1;
                const prevQuarterYear = quarter === 1 ? year - 1 : year;
                return `${prevQuarterYear}年Q${prevQuarter}`;
            case 'year':
                return `${year - 1}年`;
            default:
                return '上周期';
        }
    } else {
        // 同比数据
        switch (salesFunnelState.currentPeriod) {
            case 'month':
                return `${year - 1}年${month}月`;
            case 'quarter':
                return `${year - 1}年Q${quarter}`;
            case 'year':
                return `${year - 1}年`;
            default:
                return '去年同期';
        }
    }
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', initSalesFunnel);